using FirstTea.Application.DTOs;
using FirstTea.Application.Interfaces;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace FirstTea.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class OrderController : ControllerBase
    {
        private readonly IOrderService _orderService;
        public OrderController(IOrderService orderService)
        {
            _orderService = orderService;
        }
        [HttpGet]
        public async Task<ActionResult> GetAll()
        {
            var orders = await _orderService.GetAllAsync();
            return Ok(orders);
        }
        [HttpGet("{id}")]
        public async Task<ActionResult<OrderDto?>> GetById(Guid id)
        {
            var order = await _orderService.GetByIdAsync(id);
            if (order == null) return NotFound();
            return Ok(order);
        }

            /// <summary>
            /// 分页获取订单列表
            /// </summary>
            [HttpGet("paged")]
            public async Task<ActionResult> GetPaged([FromQuery] int page = 1, [FromQuery] int pageSize = 10)
            {
                var orders = await _orderService.GetAllAsync();
                var paged = orders.Skip((page - 1) * pageSize).Take(pageSize);
                return Ok(paged);
            }

            /// <summary>
            /// 查询指定用户的订单
            /// </summary>
            [HttpGet("user/{userId}")]
            public async Task<ActionResult> GetByUser(Guid userId)
            {
                var orders = await _orderService.GetAllAsync();
                var userOrders = orders.Where(o => o.UserId == userId);
                return Ok(userOrders);
            }

            /// <summary>
            /// 订单模糊搜索
            /// </summary>
            [HttpGet("search")]
            public async Task<ActionResult> Search([FromQuery] string keyword)
            {
                var orders = await _orderService.GetAllAsync();
                var result = orders.Where(o => o.Status != null && o.Status.Contains(keyword, StringComparison.OrdinalIgnoreCase));
                return Ok(result);
            }
        [HttpPost]
        public async Task<ActionResult> Create([FromBody] OrderDto dto)
        {
            await _orderService.CreateAsync(dto);
            return Ok();
        }
        [HttpPut]
        public async Task<ActionResult> Update([FromBody] OrderDto dto)
        {
            await _orderService.UpdateAsync(dto);
            return Ok();
        }
        [HttpDelete("{id}")]
        public async Task<ActionResult> Delete(Guid id)
        {
            await _orderService.DeleteAsync(id);
            return Ok();
        }
    }
}
